<template>
  <div class="container-fluid">
    <!-- 顶部导航栏 -->
    <header class="col-md-12 bg-primary text-white p-3">
      <div class="row justify-content-between align-items-center">
        <div class="col-md-auto">
          <h1>停车场管理系统</h1>
        </div>
        <div class="col-md-auto ml-auto">
          <span class="mr-3">{{ username }}</span>
          <router-link to="/" class="btn btn-light mr-2">返回首页</router-link>
          <button @click="logout" class="btn btn-light">退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="col-md-12 mt-4">
      <div class="card">
        <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
          <h2>车位管理</h2>
        </div>
        <div class="card-body">
          
          <!-- 搜索栏 -->
          <div class="mb-4 search-bar">
            <div class="row">
              <div class="form-group col-md-4">
                <label for="searchDescription" class="sr-only">区域搜索</label>
                <select class="form-control" id="searchDescription" v-model="searchDescription" @change="handleSearch">
                  <option value="">全部区域</option>
                  <option value="A区">A区</option>
                  <option value="B区">B区</option>
                  <option value="C区">C区</option>
                </select>
              </div>
              <div class="form-group col-md-4">
                <label for="searchStatus" class="sr-only">状态搜索</label>
                <select class="form-control" id="searchStatus" v-model="searchStatus" @change="handleSearch">
                  <option value="">全部状态</option>
                  <option value="0">空闲</option>
                  <option value="1">占用</option>
                  <option value="2">预约</option>
                  <option value="3">故障</option>
                </select>
              </div>
              <div class="form-group col-md-4">
                <label for="searchPlateNumber" class="sr-only">车牌搜索</label>
                <input type="text" class="form-control" id="searchPlateNumber" v-model="searchPlateNumber" placeholder="车牌" @input="handleSearch">
              </div>
            </div>
          </div>
          
          <!-- 车位统计信息 -->
          <div class="row mb-4">
            <div class="col-md-3">
              <div class="p-4 bg-primary text-white text-center rounded">
                <h3>总车位数</h3>
                <p class="display-4">{{ totalParkingSpots }}</p>
              </div>
            </div>
            <div class="col-md-3">
              <div class="p-4 bg-success text-white text-center rounded">
                <h3>空闲车位</h3>
                <p class="display-4">{{ freeParkingSpots }}</p>
              </div>
            </div>
            <div class="col-md-3">
              <div class="p-4 bg-warning text-white text-center rounded">
                <h3>已占用车位</h3>
                <p class="display-4">{{ occupiedParkingSpots }}</p>
              </div>
            </div>
            <div class="col-md-3">
              <div class="p-4 bg-danger text-white text-center rounded">
                <h3>故障车位</h3>
                <p class="display-4">{{ maintenanceParkingSpots }}</p>
              </div>
            </div>
          </div>
          
          <!-- 车位可视化 -->
          <div class="row mb-4">
            <div class="col-md-12">
              <!-- 标题行 - 只在这一行应用蓝色背景 -->
              <div class="p-3 bg-primary text-white mb-3">
                <h3>车位可视化</h3>
              </div>
              
              <!-- 按车位编号首字母分组显示车位 - 不应用背景色 -->
              <div v-for="(group, letter) in parkingGroups" :key="letter" class="mb-4">
                <h4 class="mb-2">{{ letter }}区车位</h4>
                <div class="flex flex-wrap" style="gap: 50px;">
                  <div 
                    v-for="parking in group" 
                    :key="parking.id"
                    class="parking-box"
                    :class="{
                      'bg-success': parking.status === 0,
                      'bg-warning': parking.status === 1,
                      'bg-danger': parking.status === 2,
                      'bg-pink': parking.status === 3
                    }"
                  >
                    <p>车位编号: {{ parking.code }}</p>
                    <p>状态: {{ getStatusText(parking.status) }}</p>
                    <p>类型: {{ getTypeText(parking.type) }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>车位编号</th>
                <th>区域</th>
                <th>类型</th>
                <th>状态</th>
                <th>车主姓名</th>
                <th>联系电话</th>
                <th>占用时间</th>
                <th>车牌号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="parking in parkingList" :key="parking.id">
                <td>{{ parking.code }}</td>
                <td>{{ parking.description || parking.area || '未分配' }}</td>
                <td>{{ getTypeText(parking.type) }}</td>
                <td>
                  <span :class="{
                    'text-success': parking.status === 0,
                    'text-danger': parking.status === 1,
                    'text-pink': parking.status === 2,
                    'text-warning': parking.status === 3
                  }">
                    {{ getStatusText(parking.status) }}
                  </span>
                </td>
                <td>{{ parking.ownerName || '-' }}</td>
                <td>{{ parking.phone || '-' }}</td>
                <td>{{ parking.occupiedTime || '-' }}</td>
                  <td>{{ parking.plateNumber || '-' }}</td> <!-- 后端没有车牌号字段，这里保持显示 '-' -->
                <td>
                  <button @click="viewParkingDetail(parking.id)" class="btn btn-info btn-sm mr-2">查看详情</button>
                  <button @click="editParking(parking.id)" class="btn btn-primary btn-sm">编辑</button>
                </td>
              </tr>
            </tbody>
          </table>
          
          <!-- 分页按钮 -->
          <div class="mt-4 d-flex justify-content-between align-items-center">
            <div>显示 {{ (this.pageNum - 1) * this.pageSize + 1 }} 到 {{ Math.min(this.pageNum * this.pageSize, this.total) }} 条，共 {{ this.total }} 条</div>
            <div>
              <button 
                class="btn btn-primary mr-2" 
                @click="prevPage"
                :disabled="this.pageNum === 1"
              >
                上一页
              </button>
              <span class="mx-2">第 {{ this.pageNum }} 页</span>
              <button class="btn btn-primary ml-2" @click="nextPage" :disabled="Math.ceil(this.total / this.pageSize) <= this.pageNum">
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from '../../utils/axios'

export default {
  name: 'ParkingManageView',
  data() {
    return {
      username: '',
      parkingList: [],
      originalParkingList: [],
      searchDescription: '',
      searchStatus: '',
      searchPlateNumber: '',
      pageNum: 1,
      pageSize: 8,
      total: 0,
      // 新添加的变量用于存储车位基本信息
      parkingBasicInfo: [],
      statusCount: {}
    }
  },
  mounted() {
    this.username = localStorage.getItem('username') || '管理员'
    this.loadParkingList()
    this.loadParkingBasicInfo()
  },
  computed: {
    // 计算总车位数
    totalParkingSpots() {
      return this.parkingBasicInfo.length
    },
    // 计算空闲车位数
    freeParkingSpots() {
      // 从对象中提取count值
      return this.statusCount[0] ? (this.statusCount[0].count || 0) : 0
    },
    // 计算已占用车位数
    occupiedParkingSpots() {
      // 从对象中提取count值
      return this.statusCount[1] ? (this.statusCount[1].count || 0) : 0
    },
    // 计算故障/维护车位数
    maintenanceParkingSpots() {
      // 从对象中提取count值
      return this.statusCount[3] ? (this.statusCount[3].count || 0) : 0
    },
    // 按车位编号首字母分组
    parkingGroups() {
      const groups = {}
      this.parkingBasicInfo.forEach(item => {
        // 确保item是有效的对象且包含code属性
        if (item && item.code) {
          const firstLetter = item.code.charAt(0)
          if (!groups[firstLetter]) {
            groups[firstLetter] = []
          }
          // 转换为前端需要的格式，并添加类型转换
          groups[firstLetter].push({
            id: item.code,
            code: item.code,
            // 确保type是数字类型
            type: Number(item.type),
            // 确保status是数字类型
            status: Number(item.status)
          })
        }
      })
      return groups
    }
  },
  methods: {
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    
    // 加载车位列表数据（用于表格显示）
    loadParkingList() {
      // 从后端API获取车位列表 - 使用基于axios.js配置的相对路径
      axios.get('/parking/info/page', {
        params: {
          pageNum: this.pageNum,
          code: this.searchPlateNumber,  // 前端的车牌号搜索对应后端的code参数
          status: this.searchStatus || undefined,
          description: this.searchDescription || undefined
        }
      }).then(response => {
        console.log('后端返回响应:', response);
        let resultData = null;
        
        // 检查response是否为有效对象
        if (response) {
          // 检查response中是否直接包含list属性（处理特殊情况）
          if (response.list && Array.isArray(response.list)) {
            console.log('直接从response中获取数据');
            resultData = response;
          }
          // 标准axios响应结构
          else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            console.log('从response.data中获取数据');
            resultData = response.data;
          }
        }
        
        if (resultData) {
          // 将后端返回的数据转换为前端可用的格式
          this.parkingList = resultData.list.map(item => ({
            id: item.code,  // 使用车位编号作为ID
            code: item.code,
            type: item.type,
            status: item.status,
            area: item.description,  // 后端的description对应前端的area
            description: item.description, // 保留原字段以便显示
            ownerName: item.ownerName || '-',
            phone: item.phone || '-',
            occupiedTime: item.entryTime ? new Date(item.entryTime).toLocaleString() : '-',  // 后端的entryTime对应前端的occupiedTime
            plateNumber: '-'  // 后端没有车牌号字段
          }))
          this.total = resultData.total || resultData.list.length
        } else {
          // 如果返回的数据格式不符合预期，显示空列表
          console.warn('返回的数据格式不符合预期')
          this.parkingList = []
          this.total = 0
        }
      })
      .catch(error => {
        console.error('获取车位列表失败:', error)
        // 如果API调用失败，显示空列表
        this.parkingList = []
        this.total = 0
      })
},
    
    // 新加载车位基本信息数据（用于可视化和统计）
    loadParkingBasicInfo() {
      // 从后端API获取车位基本信息 - 使用基于axios.js配置的相对路径
      axios.get('/parking/spaces/basic-info')
        .then(response => {
          console.log('车位基本信息响应:', response);
          // 检查response是否为有效对象
          if (response) {
            // 检查response中是否直接包含basicInfo和statusCount（处理特殊情况）
            if (response.basicInfo && response.statusCount) {
              console.log('直接从response中获取数据');
              this.parkingBasicInfo = response.basicInfo || [];
              this.statusCount = response.statusCount || {};
            } 
            // 标准axios响应结构
            else if (response.data) {
              console.log('从response.data中获取数据');
              this.parkingBasicInfo = response.data.basicInfo || [];
              this.statusCount = response.data.statusCount || {};
            } 
            else {
              console.warn('车位基本信息数据格式不符合预期');
              this.parkingBasicInfo = [];
              this.statusCount = {};
            }
          } else {
            console.warn('无效的响应对象');
            this.parkingBasicInfo = [];
            this.statusCount = {};
          }
        })
        .catch(error => {
          console.error('获取车位基本信息失败:', error);
          // 如果API调用失败
          this.parkingBasicInfo = [];
          this.statusCount = {};
        })
    },
    
    handleSearch() {
      // 重置页码并重新加载数据
      this.pageNum = 1
      this.loadParkingList()
      // 同时重新加载车位基本信息
      this.loadParkingBasicInfo()
    },
    
    editParking(id) {
      // 编辑车位逻辑
      alert(`编辑车位 ${id}`)
    },
    
    deleteParking(id) {
      // 删除车位逻辑
      if (confirm('确定要删除这个车位吗？')) {
        this.parkingList = this.parkingList.filter(parking => parking.id !== id)
        alert('删除成功')
      }
    },
    
    // 上一页
    prevPage() {
      if (this.pageNum > 1) {
        this.pageNum--
        this.loadParkingList()
      }
    },
    
    // 下一页
    nextPage() {
      if (Math.ceil(this.total / this.pageSize) > this.pageNum) {
        this.pageNum++
        this.loadParkingList()
      }
    },
    
    viewParkingDetail(id) {
      // 查看车位详情逻辑
      const parking = this.parkingList.find(p => p.id === id)
      if (parking) {
        let detailInfo = `车位详情\n`
        detailInfo += `车位编号: ${parking.code}\n`
        detailInfo += `区域: ${parking.area || '未分配'}\n`
        detailInfo += `类型: ${this.getTypeText(parking.type)}\n`
        detailInfo += `状态: ${this.getStatusText(parking.status)}\n`
        detailInfo += `车主姓名: ${parking.ownerName || '-'}\n`
        detailInfo += `联系电话: ${parking.phone || '-'}\n`
        detailInfo += `占用时间: ${parking.occupiedTime || '-'}\n`
        alert(detailInfo)
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch(status) {
        case 0: return '空闲'
        case 1: return '占用'
        case 2: return '故障'
        case 3: return '已预约'
        default: return '未知'
      }
    },
    
    getTypeText(type) {
      // 转换为数字类型进行比较
      const typeNum = Number(type);
      
      // 调试日志，可查看实际传入的值和类型
      console.log('车位类型值:', type, '类型:', typeof type, '转换后:', typeNum);
      
      switch (typeNum) {
        case 0:
          return '普通车位';
        case 1:
          return 'VIP车位';
        case 2:
          return '残疾人车位';
        default:
          return '未知类型';
      }
    }
  }
}
</script>

<style>
/* 车位盒子样式 */
.parking-box {
  width: 150px;
  height: 120px;
  padding: 10px;
  border-radius: 5px;
  color: white;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.parking-box p {
  margin: 4px 0;
}

/* 自定义粉色背景 */
.bg-pink {
  background-color: #e91e63;
}
</style>